#include <stdio.h>
#include <QtCore/QEventLoop>
#include <QtCore/QFile>
#include <QtCore/QTimer>
#include <QtCore/QUrl>
#include <QtNetwork/QHttp>
#include "qhttpclient_qhttp.h"


QHttpClient_QHttp::QHttpClient_QHttp() {
    m_bSuccess = false;
    m_pHttp = new QHttp;
    connect(m_pHttp, SIGNAL(done(bool)), this, SLOT(done(bool)));
}

QHttpClient_QHttp::~QHttpClient_QHttp() {
    m_pHttp->abort();
    m_pHttp->deleteLater();
}

void QHttpClient_QHttp::done(bool error) {
    m_bSuccess = !error;
    m_eventLoop.exit();
}

bool QHttpClient_QHttp::setProxy(const char *szServer, const int iPort,
                                 const char *szUser, const char *szPassword, const char* szDomain)
{
    if (szDomain && strlen(szDomain) != 0) {
        fprintf(stderr, "NTLM proxy is not implemented...\n");
    }

    m_pHttp->setProxy(szServer, iPort);
    if (szUser) {
        m_pHttp->setUser(szUser, szPassword);
    }
    return true;
}

bool QHttpClient_QHttp::getUrlToMem(const char *szUrl, char *szBuffer)
{
    UNUSED_PARAMETER(szUrl);
    UNUSED_PARAMETER(szBuffer);
    fprintf(stderr, "Not implemented...\n");
    return false;
}

// see: http://www.erata.net/qt-boost/synchronous-http-request/
// see: http://www.qtforum.org/article/29846/qhttp-problem-with-the-timeout.html
bool QHttpClient_QHttp::getUrlToFile(const char *szUrl, const char *szLocalFilePath)
{
    QFile file(szLocalFilePath);
    if (!file.open(QIODevice::WriteOnly)) {
        return false;
    }

    QUrl url(szUrl);
    m_pHttp->setHost(url.host());
    m_pHttp->get(url.path(), &file);

    QTimer timer;
    connect(&timer, SIGNAL(timeout()), &m_eventLoop, SLOT(quit()));
    timer.setSingleShot(true);
    timer.start(HC_TIMEOUT);
    m_eventLoop.exec();
    return m_bSuccess;
}
